<template>
  <div class="page">
    <div class="container">

      <h1 class="title">手机号校验并提交</h1>

      <form @submit.prevent="handleSubmit">

        <!-- 输入框区域 -->
        <div class="form-group">
          <label class="label">请输入手机号</label>

          <div class="input-wrapper">
            <input
              v-model="phone"
              type="text"
              class="input"
              placeholder="例如：13800138000"
              maxlength="20"
              @input="handleInput"
              @focus="error = ''"
            />

            <!-- 清除按钮 -->
            <button
              v-if="phone"
              type="button"
              class="clear-btn"
              @click="clearPhone"
            >×
            </button>
          </div>

          <p class="hint">将自动校验中国大陆手机号格式（11位，以1开头）。</p>
          <p v-if="error" class="error">{{ error }}</p>
        </div>

        <!-- 提交按钮 -->
        <button class="submit-btn" :disabled="loading">
          <template v-if="loading">
            <span class="dot"></span>
            <span class="dot"></span>
            <span class="dot"></span>
            <span>提交中</span>
          </template>
          <template v-else>提交</template>
        </button>

        <!-- 结果提示 -->
        <div v-if="resultMsg" :class="['result', success ? 'success' : 'fail']">
          {{ resultMsg }}
        </div>
      </form>

    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      phone: '',
      error: '',
      resultMsg: '',
      success: false,
      loading: false,
      regex: /^1[3-9]\d{9}$/
    }
  },

  methods: {
    handleInput() {
      // 删除空格、删除 +86、86
      let v = this.phone.replace(/\s+/g, '')
      v = v.replace(/^\+86/, '').replace(/^86/, '')
      this.phone = v
    },

    clearPhone() {
      this.phone = ''
      this.error = ''
      this.$nextTick(() => {
        this.$el.querySelector('.input').focus()
      })
    },

    validate() {
      if (!this.phone) return '手机号不能为空'
      if (!this.regex.test(this.phone)) return '手机号格式不正确'
      return ''
    },

    async handleSubmit() {
      this.error = ''
      this.resultMsg = ''
      const msg = this.validate()

      if (msg) {
        this.error = msg
        return
      }

      this.loading = true

      const body =
        `phone=` + encodeURIComponent(this.phone.trim())

      try {
        const resp = await fetch(
          'http://liujiji.nat300.top/platformServe/redis/savePhoneAlive',
          {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            body
          }
        )

        let text = await resp.text()
        let json = null

        try {
          json = JSON.parse(text)
        } catch (_) {
        }

        let ok = false

        if (json === true) {
          ok = true
        } else if (json && typeof json === 'object') {
          ok = json.success || json.ok
        } else {
          text = text.trim().toLowerCase()
          ok =
            text === 'true' ||
            text === 'success' ||
            text === 'ok'
        }

        this.success = ok
        this.resultMsg = ok ? '提交成功，手机号已保存' : `提交失败：${text}`

      } catch (e) {
        this.success = false
        this.resultMsg = '请求失败：' + e.message
      }

      this.loading = false
    }
  }
}
</script>

<style scoped>
/* ============ 移动端布局 ============ */
.page {
  width: 100%;
  min-height: 100vh;
  background: #f7f7f7;
  padding: 16px;
  box-sizing: border-box;
}

.container {
  background: #fff;
  padding: 22px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.07);
  max-width: 500px;
  margin: auto;
}

/* 标题 */
.title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  padding-left: 10px;
  border-left: 4px solid #2d8cf0;
  margin-bottom: 22px;
}

/* 输入相关 */
.form-group {
  margin-bottom: 20px;
}

.label {
  display: block;
  color: #333;
  margin-bottom: 8px;
  font-size: 15px;
}

.input-wrapper {
  position: relative;
}

.input {
  width: 100%;
  padding: 12px 14px;
  padding-right: 32px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  outline: none;
  transition: .3s;
}

.input:focus {
  border-color: #2d8cf0;
  box-shadow: 0 0 0 3px rgba(45, 140, 240, 0.12);
}

/* 清除按钮 */
.clear-btn {
  position: absolute;
  right: 6px;
  top: 50%;
  transform: translateY(-50%);
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: none;
  background: #eaeaea;
  font-size: 15px;
  line-height: 1;
  cursor: pointer;
}

/* 提示与错误 */
.hint {
  margin-top: 6px;
  font-size: 13px;
  color: #666;
}

.error {
  margin-top: 6px;
  color: #c20000;
  font-size: 13px;
}

/* 提交按钮 */
.submit-btn {
  width: 100%;
  margin-top: 12px;
  padding: 13px;
  font-size: 16px;
  border: none;
  border-radius: 8px;
  background: #2d8cf0;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 6px;
  transition: .3s;
}

.submit-btn:disabled {
  background: #a5c9f8;
}

/* 加载小点动画 */
.dot {
  display: inline-block;
  width: 7px;
  height: 7px;
  background: #fff;
  border-radius: 50%;
  animation: dot 1.3s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes dot {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

/* 结果提示 */
.result {
  margin-top: 14px;
  padding: 10px 12px;
  border-radius: 8px;
  font-size: 14px;
}

.success {
  color: #0a8a3f;
  background: rgba(10, 138, 63, 0.08);
}

.fail {
  color: #c20000;
  background: rgba(194, 0, 0, 0.08);
}
</style>
